/** \file
* Platform-independent implementations for the debug console class.
* This file is part of Chorus, available at
* http://code.google.com/p/chorus-twitter/ . This file and all associated files
* and derivative works are bound by the terms of the LGPL 3.0 license,
* available at http://www.gnu.org/licenses/lgpl-3.0-standalone.html .
* \par Subversion URL:
* \$URL: http://chorus-twitter.googlecode.com/svn/branches/cpp/src/system/DebugConsole.cpp $
* \version \$Rev: 152 $
* \date    \$Date: 2010-04-06 07:35:13 +0000 (Tue, 06 Apr 2010) $
*/

#include "config.h"

#ifdef USING_DEBUGCONSOLE


#include <iomanip>
#include <cstring>
#include <errno.h>


#include <libxml/parser.h>

#include "system/Timer.hpp"
#include "system/Thread.hpp"
#include "system/DebugConsole.hpp"

using namespace std;

void DebugConsole::addStream(std::ostream *stream)
{
	streams.push_back(stream);
}

void DebugConsole::printStandard(
	const char *file,
	const char *function,
	int line,
	const char *message)
{
	buffer
		<< "\nT=0x" << left << hex << setw(8) << setfill(' ')
		<< Thread::getCurrentThreadID() << dec << "  "
		<< setprecision(9) << fixed << timerglob->getTimeDouble() << "s  "
		<< function << "()\n"
		<< file << '(' << line << ") : " << message << '\n';
}

void DebugConsole::flush()
{
	const string &str = buffer.str();
	for (std::list<std::ostream*>::iterator i = streams.begin();
		i != streams.end();
		i++)
		**i << str;
	buffer.str("");
}


template <>
void DebugConsole::Print2::print(std::ostringstream &buffer, void *message2)
{
	buffer << "    0x" << hex << (unsigned long)message2 << dec << '\n';
}

void DebugConsole::PrintCErrno::print(std::ostringstream &buffer)
{
	buffer << "    " << errno << ": " << strerror(errno) << '\n';
}

void DebugConsole::PrintCCode::print(std::ostringstream &buffer, int code)
{
	buffer << "    " << code << ": " << strerror(code) << '\n';
}

void DebugConsole::PrintXml::print(std::ostringstream &buffer)
{
	const xmlError *const xerror = xmlGetLastError();
	if (xerror)
		buffer << "    " << xerror->code << ": " << xerror->message << '\n';
	else
		buffer << "    Unknown error\n";
}

#endif // #ifdef USING_DEBUGCONSOLE
